<script setup lang="ts">
import { ref } from 'vue'
import { i18n } from 'boot/i18n'

const tc = i18n.global.tc

// 权限列表
const permissions = [
  { key: 'book_meeting', name: tc('预定会议'), description: tc('允许用户预定会议资源') },
  { key: 'view_all_meetings', name: tc('查看所有会议'), description: tc('允许查看所有用户的会议预定') },
  { key: 'modify_meetings', name: tc('修改会议'), description: tc('允许修改会议预定信息') },
  { key: 'release_meetings', name: tc('释放会议资源'), description: tc('允许释放已预定的会议资源') },
  { key: 'manage_users', name: tc('管理用户'), description: tc('允许添加、编辑和删除用户') },
  { key: 'manage_roles', name: tc('管理角色'), description: tc('允许创建和修改角色及权限') },
  { key: 'manage_groups', name: tc('管理分组'), description: tc('允许创建和修改用户分组') },
  { key: 'system_settings', name: tc('系统设置'), description: tc('允许修改系统配置') }
]

// 模拟角色数据
const roles = ref([
  {
    id: 1,
    name: '系统管理员',
    description: '拥有所有权限的超级管理员',
    permissions: ['book_meeting', 'view_all_meetings', 'modify_meetings', 'release_meetings', 'manage_users', 'manage_roles', 'manage_groups', 'system_settings'],
    userCount: 3
  },
  {
    id: 2,
    name: '部门管理员',
    description: '可管理部门内用户和会议',
    permissions: ['book_meeting', 'view_all_meetings', 'modify_meetings', 'release_meetings', 'manage_users'],
    userCount: 8
  },
  {
    id: 3,
    name: '普通用户',
    description: '基本会议预定功能',
    permissions: ['book_meeting'],
    userCount: 120
  },
  {
    id: 4,
    name: '预定员',
    description: '可代为他人预定会议',
    permissions: ['book_meeting', 'modify_meetings'],
    userCount: 15
  }
])

// 正在编辑的角色
const editedRole = ref(null)
const isNewRole = ref(false)

// 角色编辑对话框
const roleDialog = ref(false)

// 删除确认对话框
const deleteConfirmDialog = ref(false)
const roleToDelete = ref(null)

// 编辑角色
const editRole = (role) => {
  editedRole.value = JSON.parse(JSON.stringify(role)) // 深拷贝避免直接修改原数据
  isNewRole.value = false
  roleDialog.value = true
}

// 创建新角色
const createRole = () => {
  editedRole.value = {
    id: Math.max(...roles.value.map(r => r.id)) + 1,
    name: '',
    description: '',
    permissions: [],
    userCount: 0
  }
  isNewRole.value = true
  roleDialog.value = true
}

// 保存角色
const saveRole = () => {
  if (!editedRole.value) return

  if (isNewRole.value) {
    // 添加新角色
    roles.value.push(editedRole.value)
  } else {
    // 更新现有角色
    const index = roles.value.findIndex(r => r.id === editedRole.value.id)
    if (index !== -1) {
      roles.value[index] = editedRole.value
    }
  }

  roleDialog.value = false
  editedRole.value = null
}

// 弹出删除确认
const confirmDeleteRole = (role) => {
  roleToDelete.value = role
  deleteConfirmDialog.value = true
}

// 删除角色
const deleteRole = () => {
  if (!roleToDelete.value) return

  const index = roles.value.findIndex(r => r.id === roleToDelete.value.id)
  if (index !== -1) {
    roles.value.splice(index, 1)
  }

  deleteConfirmDialog.value = false
  roleToDelete.value = null
}

// 权限是否包含
const hasPermission = (role, permKey) => {
  return role.permissions.includes(permKey)
}

// 切换角色的权限
const togglePermission = (permKey) => {
  if (!editedRole.value) return

  const index = editedRole.value.permissions.indexOf(permKey)
  if (index !== -1) {
    editedRole.value.permissions.splice(index, 1)
  } else {
    editedRole.value.permissions.push(permKey)
  }
}
</script>

<template>
  <q-scroll-area style="height: calc(100vh - 50px)">
    <div class="q-pa-md">
      <h5 class="q-mt-none q-mb-md">{{ tc('角色管理') }}</h5>

      <!-- 工具栏 -->
      <div class="row q-mb-md items-center">
        <div class="col">
          <q-btn
            color="primary"
            :label="tc('创建角色')"
            icon="add"
            @click="createRole"
          />
        </div>
      </div>

      <!-- 角色列表 -->
      <q-card>
        <q-card-section>
          <q-table
            :rows="roles"
            :columns="[
              { name: 'name', label: tc('角色名称'), field: 'name', align: 'left', sortable: true },
              { name: 'description', label: tc('描述'), field: 'description', align: 'left' },
              { name: 'userCount', label: tc('用户数'), field: 'userCount', align: 'center', sortable: true },
              { name: 'permissions', label: tc('权限'), field: 'permissions', align: 'left' },
              { name: 'actions', label: tc('操作'), field: 'id', align: 'center' }
            ]"
            row-key="id"
            :pagination="{ rowsPerPage: 10 }"
          >
            <!-- 权限列 -->
            <template v-slot:body-cell-permissions="props">
              <q-td :props="props">
                <div class="row q-gutter-xs">
                  <q-badge
                    v-for="perm in props.row.permissions.slice(0, 2)"
                    :key="perm"
                    color="primary"
                    class="q-px-sm"
                  >
                    {{ permissions.find(p => p.key === perm)?.name || perm }}
                  </q-badge>

                  <q-badge
                    v-if="props.row.permissions.length > 2"
                    color="grey"
                    class="q-px-sm"
                  >
                    +{{ props.row.permissions.length - 2 }}
                  </q-badge>
                </div>
              </q-td>
            </template>

            <!-- 操作列 -->
            <template v-slot:body-cell-actions="props">
              <q-td :props="props">
                <q-btn
                  flat
                  round
                  color="primary"
                  icon="edit"
                  size="sm"
                  @click="editRole(props.row)"
                >
                  <q-tooltip>{{ tc('编辑权限') }}</q-tooltip>
                </q-btn>

                <q-btn
                  flat
                  round
                  color="negative"
                  icon="delete"
                  size="sm"
                  :disable="props.row.userCount > 0"
                  @click="confirmDeleteRole(props.row)"
                >
                  <q-tooltip>
                    {{ props.row.userCount > 0 ? tc('有用户关联，无法删除') : tc('删除角色') }}
                  </q-tooltip>
                </q-btn>
              </q-td>
            </template>
          </q-table>
        </q-card-section>
      </q-card>

      <!-- 角色编辑对话框 -->
      <q-dialog v-model="roleDialog" persistent>
        <q-card style="min-width: 600px">
          <q-card-section class="row items-center">
            <div class="text-h6">{{ isNewRole ? tc('创建角色') : tc('编辑角色') }}</div>
            <q-space />
            <q-btn icon="close" flat round dense v-close-popup />
          </q-card-section>

          <q-card-section v-if="editedRole">
            <q-form>
              <div class="row q-col-gutter-md">
                <!-- 角色名称 -->
                <div class="col-12">
                  <q-input
                    v-model="editedRole.name"
                    :label="tc('角色名称') + ' *'"
                    outlined
                    dense
                    required
                  />
                </div>

                <!-- 角色描述 -->
                <div class="col-12">
                  <q-input
                    v-model="editedRole.description"
                    :label="tc('角色描述')"
                    outlined
                    dense
                    type="textarea"
                    autogrow
                  />
                </div>

                <!-- 权限设置 -->
                <div class="col-12">
                  <div class="text-subtitle2 q-mb-sm">{{ tc('权限设置') }}</div>

                  <q-list bordered separator>
                    <q-item v-for="perm in permissions" :key="perm.key">
                      <q-item-section avatar>
                        <q-checkbox
                          :model-value="hasPermission(editedRole, perm.key)"
                          @update:model-value="togglePermission(perm.key)"
                        />
                      </q-item-section>

                      <q-item-section>
                        <q-item-label>{{ perm.name }}</q-item-label>
                        <q-item-label caption>{{ perm.description }}</q-item-label>
                      </q-item-section>
                    </q-item>
                  </q-list>
                </div>
              </div>
            </q-form>
          </q-card-section>

          <q-card-actions align="right">
            <q-btn flat :label="tc('取消')" color="grey" v-close-popup />
            <q-btn :label="tc('保存')" color="primary" @click="saveRole" />
          </q-card-actions>
        </q-card>
      </q-dialog>

      <!-- 删除确认对话框 -->
      <q-dialog v-model="deleteConfirmDialog">
        <q-card>
          <q-card-section class="row items-center">
            <div class="text-h6">{{ tc('确认删除') }}</div>
          </q-card-section>

          <q-card-section v-if="roleToDelete">
            <p>{{ tc('您确定要删除角色') }} "{{ roleToDelete.name }}" {{ tc('吗？') }}</p>
            <p class="text-negative">{{ tc('此操作无法撤销。') }}</p>
          </q-card-section>

          <q-card-actions align="right">
            <q-btn flat :label="tc('取消')" color="grey" v-close-popup />
            <q-btn :label="tc('删除')" color="negative" @click="deleteRole" />
          </q-card-actions>
        </q-card>
      </q-dialog>
    </div>
  </q-scroll-area>
</template>
